import { Button, message, Modal, Input, Tag, Row, Col } from "antd";
import { useEffect, useState } from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';

/**
 * 页面权限搜索模态框组件
 *
 * @param props
 * @constructor
 */
const PagePermissionSelect = (props) => {
    const {
        visible,
        setVisible,
        consolePages,
        setConsolePages
    } = props;

    const [messageApi, contextHolder] = message.useMessage();
    // 已经选中的页面权限
    const [selectedPagePermissions, setSelectedPagePermissions] = useState([]);
    // 所有页面权限集合
    const [allPagePermissions, setAllPagePermissions] = useState([]);
    // 左侧搜索框值
    const [leftSearchValue, setLeftSearchValue] = useState('');
    // 右侧搜索框值
    const [rightSearchValue, setRightSearchValue] = useState('');

    /**
     * 查询所有页面权限集合
     */
    const searchAllPagePermissions = () => {
        RequestUtils.post(RequestApis.permissionManage.listPagePermission, {})
            .then(res => {
                setAllPagePermissions(res.data.data);
            })
            .catch(err => messageApi.error(err.message));
    }

    useEffect(() => {
        if (visible) {
            setSelectedPagePermissions([...consolePages]);
            searchAllPagePermissions();
        }
        // eslint-disable-next-line
    }, [visible]);

    /**
     * 获取未选中的权限列表（用于左侧显示）
     */
    const getUnselectedPermissions = () => {
        return allPagePermissions.filter(perm =>
            !selectedPagePermissions.some(selected => selected.pageCode === perm.pageCode)
        );
    };

    /**
     * 添加权限到右侧
     * @param permission 要添加的权限
     */
    const addPermission = (permission) => {
        if (!selectedPagePermissions.some(item => item.pageCode === permission.pageCode)) {
            setSelectedPagePermissions(prev => [...prev, permission]);
        }
    };

    /**
     * 从右侧移除权限
     * @param permission 要移除的权限
     */
    const removePermission = (permission) => {
        setSelectedPagePermissions(prev =>
            prev.filter(item => item.pageCode !== permission.pageCode)
        );
    };

    /**
     * 过滤权限列表
     * @param permissions 权限列表
     * @param searchValue 搜索关键词
     * @returns 过滤后的权限列表
     */
    const filterPermissions = (permissions, searchValue) => {
        if (!searchValue) return permissions;
        return permissions.filter(perm =>
            perm.pageName.toLowerCase().includes(searchValue.toLowerCase()) ||
            perm.module.toLowerCase().includes(searchValue.toLowerCase()) ||
            perm.pageCode.toLowerCase().includes(searchValue.toLowerCase())
        );
    };

    return (
        <Modal
            title="选择页面权限"
            open={visible}
            width={1000}
            onCancel={() => setVisible(false)}
            footer={
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
                    <Button
                        type="primary"
                        onClick={() => {
                            setConsolePages(selectedPagePermissions);
                            setVisible(false);
                        }}
                    >
                        确认选择 ({selectedPagePermissions.length})
                    </Button>
                    <Button
                        danger
                        onClick={() => {
                            setVisible(false);
                        }}
                    >
                        取消
                    </Button>
                </div>
            }
            styles={{
                body: {
                    background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
                    padding: '20px'
                }
            }}
        >
            {contextHolder}

            {/* 主容器 */}
            <div style={{
                display: 'flex',
                gap: '20px',
                height: '450px',
                backgroundColor: 'white',
                borderRadius: '16px',
                padding: '20px',
                boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
                border: '1px solid rgba(255, 255, 255, 0.2)'
            }}>

                {/* 左侧 - 所有权限 */}
                <div style={{
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                    backgroundColor: '#f8f9ff',
                    borderRadius: '12px',
                    padding: '16px',
                    border: '2px solid #e0e7ff'
                }}>
                    <div style={{
                        marginBottom: '16px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between'
                    }}>
                        <h3 style={{
                            margin: 0,
                            color: '#4f46e5',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}>
                            所有页面权限
                        </h3>
                        <Tag color="#4f46e5" style={{ borderRadius: '20px', fontSize: '12px' }}>
                            {filterPermissions(getUnselectedPermissions(), leftSearchValue).length} 项
                        </Tag>
                    </div>

                    {/* 左侧搜索框 */}
                    <Input
                        placeholder="搜索权限..."
                        prefix={<SearchOutlined />}
                        value={leftSearchValue}
                        onChange={(e) => setLeftSearchValue(e.target.value)}
                        style={{
                            marginBottom: '16px',
                            borderRadius: '25px',
                            border: '2px solid #c7d2fe',
                            padding: '8px 16px'
                        }}
                    />

                    {/* 左侧权限列表 */}
                    <div style={{
                        flex: 1,
                        overflowY: 'auto',
                        maxHeight: '350px',
                        paddingRight: '8px'
                    }}>
                        {filterPermissions(getUnselectedPermissions(), leftSearchValue).map((permission) => (
                            <div
                                key={permission.pageCode}
                                onClick={() => addPermission(permission)}
                                style={{
                                    padding: '12px',
                                    margin: '4px 0',
                                    borderRadius: '12px',
                                    cursor: 'pointer',
                                    background: 'linear-gradient(135deg, #ffffff 0%, #f8fafc 100%)',
                                    border: '2px solid #e2e8f0',
                                    transition: 'all 0.3s ease',
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center'
                                }}
                                onMouseEnter={(e) => {
                                    e.target.style.transform = 'translateY(-2px)';
                                    e.target.style.boxShadow = '0 8px 25px rgba(79, 70, 229, 0.15)';
                                    e.target.style.borderColor = '#4f46e5';
                                }}
                                onMouseLeave={(e) => {
                                    e.target.style.transform = 'translateY(0)';
                                    e.target.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
                                    e.target.style.borderColor = '#e2e8f0';
                                }}
                            >
                                <div>
                                    <div style={{
                                        fontWeight: 'bold',
                                        color: '#1e293b',
                                        fontSize: '14px'
                                    }}>
                                        {permission.pageName}
                                    </div>
                                    <div style={{
                                        fontSize: '12px',
                                        color: '#64748b',
                                        marginTop: '4px'
                                    }}>
                                        {permission.module}
                                    </div>
                                </div>
                                <div style={{
                                    fontSize: '12px',
                                    color: '#94a3b8',
                                    background: '#f1f5f9',
                                    padding: '4px 8px',
                                    borderRadius: '12px',
                                    fontWeight: 'bold'
                                }}>
                                    {permission.pageCode}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* 右侧 - 已选权限 */}
                <div style={{
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                    backgroundColor: '#fff5f5',
                    borderRadius: '12px',
                    padding: '16px',
                    border: '2px solid #fecaca'
                }}>
                    <div style={{
                        marginBottom: '16px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between'
                    }}>
                        <h3 style={{
                            margin: 0,
                            color: '#dc2626',
                            fontSize: '16px',
                            fontWeight: 'bold'
                        }}>
                            已选页面权限
                        </h3>
                        <Tag color="#dc2626" style={{ borderRadius: '20px', fontSize: '12px' }}>
                            {filterPermissions(selectedPagePermissions, rightSearchValue).length} 项
                        </Tag>
                    </div>

                    {/* 右侧搜索框 */}
                    <Input
                        placeholder="搜索已选..."
                        prefix={<SearchOutlined />}
                        value={rightSearchValue}
                        onChange={(e) => setRightSearchValue(e.target.value)}
                        style={{
                            marginBottom: '16px',
                            borderRadius: '25px',
                            border: '2px solid #fecaca',
                            padding: '8px 16px'
                        }}
                    />

                    {/* 右侧权限卡片网格 */}
                    <div style={{
                        flex: 1,
                        overflowY: 'auto',
                        maxHeight: '350px',
                        paddingRight: '8px'
                    }}>
                        <Row gutter={[12, 12]}>
                            {filterPermissions(selectedPagePermissions, rightSearchValue).map((permission) => (
                                <Col span={8} key={permission.pageCode}>
                                    <div
                                        style={{
                                            backgroundColor: 'white',
                                            borderRadius: '12px',
                                            padding: '12px',
                                            border: '2px solid #fecaca',
                                            position: 'relative',
                                            transition: 'all 0.3s ease',
                                            cursor: 'pointer'
                                        }}
                                        onClick={() => removePermission(permission)}
                                        onMouseEnter={(e) => {
                                            e.target.style.transform = 'translateY(-2px)';
                                            e.target.style.boxShadow = '0 8px 25px rgba(220, 38, 38, 0.2)';
                                        }}
                                        onMouseLeave={(e) => {
                                            e.target.style.transform = 'translateY(0)';
                                            e.target.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
                                        }}
                                    >
                                        <CloseOutlined
                                            style={{
                                                position: 'absolute',
                                                top: '8px',
                                                right: '8px',
                                                fontSize: '12px',
                                                color: '#dc2626',
                                                background: '#fee2e2',
                                                borderRadius: '50%',
                                                padding: '2px',
                                                cursor: 'pointer'
                                            }}
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                removePermission(permission);
                                            }}
                                        />
                                        <div style={{
                                            fontWeight: 'bold',
                                            color: '#dc2626',
                                            fontSize: '13px',
                                            marginBottom: '4px'
                                        }}>
                                            {permission.pageName}
                                        </div>
                                        <div style={{
                                            fontSize: '11px',
                                            color: '#dc2626',
                                            marginBottom: '4px'
                                        }}>
                                            {permission.module}
                                        </div>
                                        <div style={{
                                            fontSize: '10px',
                                            color: '#ef4444',
                                            background: '#fee2e2',
                                            padding: '2px 6px',
                                            borderRadius: '8px',
                                            display: 'inline-block'
                                        }}>
                                            {permission.pageCode}
                                        </div>
                                    </div>
                                </Col>
                            ))}
                        </Row>
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default PagePermissionSelect;



